package com.cll.learn.monitor.thread;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/9/29 9:29
 */
public class BaseThreadFactory implements ThreadFactory {

    private static final Logger logger = LoggerFactory.getLogger(BaseThreadFactory.class);

    /**
     * 线程池数量
     */
    private static final AtomicInteger FACTORY_NUMBER = new AtomicInteger(1);
    /**
     * 归属的线程组。不同线程组之间不能进行数据堆栈的交互
     */
    private final ThreadGroup group;
    /**
     * 线程数量
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    /**
     * 线程名称前缀
     * 线程名称:cllThreadPool[1]-[归档数据线程组]-[归档数据][2]
     */
    private final String threadNamePrefix;

    public BaseThreadFactory(String threadGroupName, String threadName) {
        group = new ThreadGroup(threadGroupName);
        threadNamePrefix = "defaultThreadFactory[" + FACTORY_NUMBER.getAndIncrement() + "]-[" + threadGroupName + "]-[" + threadName + "]-";
    }

    @Override
    public Thread newThread(Runnable r) {
        BaseTask t = new BaseTask(group, r, threadNamePrefix + threadNumber.getAndIncrement());
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("create thread. r={}; threadGroup = {}; threadName = {}; ", JSONObject.toJSONString(r), group.getName(), t.getName());
        }
        return t;
    }
}